﻿using System;
using EMANIFEST.DataAccess.Models;
using EMANIFEST.Dtos;
using System.Collections.Generic;

namespace EMANIFEST.DataAccess
{
    public partial class BusinessDataAccess
    {

        #region Import GeneralDeclaration

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportGeneralDeclarationData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // General declaration
                ImportGeneralDeclarationData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhập bản khai chung");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import general declaration object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportGeneralDeclarationData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.GeneralDeclarations != null)
            {
                foreach (var item in documentDto.GeneralDeclarations)
                {
                    item.IsTemp = isTemp;
                    SaveGeneralDeclaration_Sub(item);
                }
            }
        }

        #endregion

        #region Import HouseBill

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportHouseBillData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // General declaration
                ImportHouseBillData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhật vận đơn gom hàng");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import house bill object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportHouseBillData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.HouseBills != null)
            {
                foreach (var item in documentDto.HouseBills)
                {
                    item.IsTemp = isTemp;
                    ImportHouseBillXML(item, documentDto.UploadType);
                    //ImportHouseBillDetail_Sub(item, documentDto.UploadType);
                }
            }
        }

        /// <summary>
        /// Add GoodDeclaration object
        /// </summary>
        /// <param name="goodDeclarationDto"></param>
        /// <returns></returns>
        private void ImportHouseBillDetail_Sub(HouseBillDto houseBillDto, enumUploadType uploadType)
        {
            houseBillDto.IsTemp = IsSubmitDocument(houseBillDto.DocumentId);

            // Update document status
            if (houseBillDto.IsTemp)
            {
                SetDocumentStatusUpdate(houseBillDto.DocumentId, enumDocumentUpdate.HouseBill);
            }

            var get = GetHouseBillModelByHouseBillNo(houseBillDto.DocumentId, houseBillDto.CreaterId, houseBillDto.BillNumber, houseBillDto.IsTemp);

            if (get != null)
            {
                // Update
                //get.HouseBillId = houseBillDto.HouseBillId;
                //get.DocumentId = houseBillDto.DocumentId;
                get.Consigner = houseBillDto.Consignee;
                get.Consignee = houseBillDto.Consignee;
                get.PortOfTranship = houseBillDto.PortIdOfTranship;
                get.PortOfDestination = houseBillDto.PortIdOfDestination;
                get.PortOfLoad = houseBillDto.PortIdOfLoad;
                get.PortOfUnload = houseBillDto.PortIdOfUnload;
                get.BillNumber = houseBillDto.BillNumber;
                get.DateOfBill = houseBillDto.DateOfBill;
                get.MasterBillNo = houseBillDto.MasterBillNo;
                get.DateOfMasterBill = houseBillDto.DateOfMasterBill;
                if (uploadType == enumUploadType.Addition)
                {
                    get.NumberOfPackage += houseBillDto.NumberOfPackage;
                    get.KindOfPackages += houseBillDto.KindOfPackages;
                }
                else
                {
                    get.NumberOfPackage = houseBillDto.NumberOfPackage;
                    get.KindOfPackages = houseBillDto.KindOfPackages;
                }
                get.DepartureDate = houseBillDto.DepartureDate;
                get.CreaterId = houseBillDto.CreaterId;
                get.CreatedDate = houseBillDto.CreatedDate;
                get.ItemStatus = houseBillDto.ItemStatus;
                get.IsTemp = houseBillDto.IsTemp;

                // Delete all good item
                if (uploadType == enumUploadType.Replace || uploadType == enumUploadType.Cancellation || uploadType == enumUploadType.Original)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.HouseBillItems)
                    {
                        lstGuidId.Add(item.HouseBillItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteHouseBillItem(id);
                    }
                    if (uploadType == enumUploadType.Cancellation)
                        DeleteHouseBill(get.HouseBillId);
                }

                if (uploadType == enumUploadType.Replace || uploadType == enumUploadType.Original || uploadType == enumUploadType.Addition)
                {
                    // Add and Update
                    foreach (var item in houseBillDto.HouseBillItems)
                    {
                        get.HouseBillItems.Add(ConvertHouseBillItemDtoToModel(item));
                    }
                }
            }
            else
            {
                if (uploadType != enumUploadType.Cancellation)
                {
                    // Insert
                    get = ConvertHouseBillDtoToModel(houseBillDto);

                    // Add and Update
                    foreach (var item in houseBillDto.HouseBillItems)
                    {
                        get.HouseBillItems.Add(ConvertHouseBillItemDtoToModel(item));
                    }

                    eManifestModel.HouseBills.AddObject(get);
                }
            }
        }

        #endregion

        #region Import GoodDeclaration

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportGoodDeclarationData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // Good declaration
                ImportGoodDeclarationData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhật bản khai hàng hóa");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import good declaration object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportGoodDeclarationData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.GoodDeclarations != null)
            {
                foreach (var item in documentDto.GoodDeclarations)
                {
                    item.IsTemp = isTemp;
                    //ImportGoodDeclarationDetail_Sub(item, documentDto.UploadType);
                    ImportGoodDeclarationXMLDetail(item, documentDto.UploadType);
                }
            }
        }

        /// <summary>
        /// Add GoodDeclaration object
        /// </summary>
        /// <param name="goodDeclarationDto"></param>
        /// <returns></returns>
        private void ImportGoodDeclarationDetail_Sub(GoodDeclarationDto goodDeclarationDto, enumUploadType uploadType)
        {
            goodDeclarationDto.IsTemp = IsSubmitDocument(goodDeclarationDto.DocumentId);

            // Update document status
            if (goodDeclarationDto.IsTemp)
            {
                SetDocumentStatusUpdate(goodDeclarationDto.DocumentId, enumDocumentUpdate.GoodDeclaration);
            }

            var get = GetGoodDeclarationModelByDocumentId(goodDeclarationDto.DocumentId, goodDeclarationDto.CreaterId, goodDeclarationDto.IsTemp);

            if (get != null)
            {
                // Update
                get.Decription = goodDeclarationDto.Decription;
                get.NumberOfPackage = goodDeclarationDto.NumberOfPackage;
                get.KindOfPackages = goodDeclarationDto.KindOfPackages;
                get.CreaterId = goodDeclarationDto.CreaterId;
                get.CreatedDate = goodDeclarationDto.CreatedDate;
                get.ItemStatus = goodDeclarationDto.ItemStatus;
                get.DocumentId = goodDeclarationDto.DocumentId;
                get.ModifyId = goodDeclarationDto.ModifyId;
                get.IsTemp = goodDeclarationDto.IsTemp;

                // Delete all good item
                if (uploadType == enumUploadType.Replace || uploadType == enumUploadType.Cancellation || uploadType == enumUploadType.Original)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.GoodItems)
                    {
                        lstGuidId.Add(item.GoodItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteGoodItem(id);
                    }
                }

                if (uploadType == enumUploadType.Replace || uploadType == enumUploadType.Original || uploadType == enumUploadType.Addition)
                {
                    // Add and Update
                    foreach (var item in goodDeclarationDto.GoodItems)
                    {
                        get.GoodItems.Add(ConvertGoodItemDtoToModel(item));
                    }
                }
            }
            else
            {
                if (uploadType != enumUploadType.Cancellation)
                {
                    // Insert general declaration
                    get = ConvertGoodDeclarationDtoToModel(goodDeclarationDto);

                    // Add and Update
                    foreach (var item in goodDeclarationDto.GoodItems)
                    {
                        get.GoodItems.Add(ConvertGoodItemDtoToModel(item));
                    }

                    eManifestModel.GoodDeclarations.AddObject(get);
                }
            }
        }

        #endregion

        #region Import DangerousGood

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportDangerousGoodData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // Dangerous good
                ImportDangerousGoodData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhập bản khai hàng hóa nguy hiểm");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import dangerous good object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportDangerousGoodData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.DangerousGoods != null)
            {
                foreach (var item in documentDto.DangerousGoods)
                {
                    item.IsTemp = isTemp;
                    ImportDangerousGoodXML(item, documentDto.UploadType);
                    //ImportDangerousGoodDetail_Sub(item, documentDto.UploadType);
                }
            }
        }

        /// <summary>
        /// Save DangerousGood object
        /// </summary>
        /// <param name="dangerousGoodDto"></param>
        /// <returns></returns>
        private void ImportDangerousGoodDetail_Sub(DangerousGoodDto dangerousGoodDto, enumUploadType uploadType)
        {
            // Check document submited
            dangerousGoodDto.IsTemp = IsSubmitDocument(dangerousGoodDto.DocumentId);

            // Update document status
            if (dangerousGoodDto.IsTemp)
            {
                SetDocumentStatusUpdate(dangerousGoodDto.DocumentId, enumDocumentUpdate.DangerousGood);
            }

            var get = GetDangerousGoodModelByContainerNo(dangerousGoodDto.DocumentId, dangerousGoodDto.CreaterId, dangerousGoodDto.ContNumber, dangerousGoodDto.IsTemp);

            if (get != null)
            {
                // Update                
                get.PortOfLoad = dangerousGoodDto.PortOfLoad;
                get.PortOfUnload = dangerousGoodDto.PortOfUnload;
                get.ContNumber = dangerousGoodDto.ContNumber;
                get.ContSealNumber = dangerousGoodDto.ContSealNumber;
                get.ItemStatus = dangerousGoodDto.ItemStatus;
                get.CreaterId = dangerousGoodDto.CreaterId;
                get.DocumentId = dangerousGoodDto.DocumentId;
                get.ModifyId = dangerousGoodDto.ModifyId;
                get.IsTemp = dangerousGoodDto.IsTemp;

                if (uploadType == enumUploadType.Replace)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.DangerousGoodItems)
                    {
                        lstGuidId.Add(item.DangerousGoodItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteDangerousGoodItem(id);
                    }
                }

                // Add and Update
                foreach (var item in dangerousGoodDto.DangerousGoodItems)
                {
                    get.DangerousGoodItems.Add(ConvertDangerousGoodItemDtoToModel(item));
                }
            }
            else
            {
                // Insert
                get = ConvertDangerousGoodDtoToModel(dangerousGoodDto);

                // Add and Update
                foreach (var item in dangerousGoodDto.DangerousGoodItems)
                {
                    get.DangerousGoodItems.Add(ConvertDangerousGoodItemDtoToModel(item));
                }

                eManifestModel.DangerousGoods.AddObject(get);
            }
        }

        #endregion

        #region Import ShipStoreDeclaration

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportShipStoreDeclarationData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // Ship store declaration
                ImportShipStoreDeclarationData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhập bản khai dự trữ tàu");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import ship store declaration object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportShipStoreDeclarationData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.ShipStoreDeclarations != null)
            {
                foreach (var item in documentDto.ShipStoreDeclarations)
                {
                    item.IsTemp = isTemp;
                    //ImportShipStoreDeclarationDetail_Sub(item, documentDto.UploadType);

                    ImportShipStoreDeclarationXML(item, documentDto.UploadType);
                }
            }
        }

        /// <summary>
        /// Save ShipStoreDeclaration object
        /// </summary>
        /// <param name="shipStoreDeclarationDto"></param>
        /// <returns></returns>
        private void ImportShipStoreDeclarationDetail_Sub(ShipStoreDeclarationDto shipStoreDeclarationDto, enumUploadType uploadType)
        {
            shipStoreDeclarationDto.IsTemp = IsSubmitDocument(shipStoreDeclarationDto.DocumentId);

            // Update document status
            if (shipStoreDeclarationDto.IsTemp)
            {
                SetDocumentStatusUpdate(shipStoreDeclarationDto.DocumentId, enumDocumentUpdate.ShipStoreDeclaration);
            }

            var get = GetShipStoreDeclarationModelByDocumentId(shipStoreDeclarationDto.DocumentId, shipStoreDeclarationDto.CreaterId, shipStoreDeclarationDto.IsTemp);

            if (get != null)
            {
                // Update
                get.PeriodOfStay = shipStoreDeclarationDto.PeriodOfStay;
                get.PlaceOfStorage = shipStoreDeclarationDto.PlaceOfStorage;
                get.CreaterId = shipStoreDeclarationDto.CreaterId;
                get.CreatedDate = shipStoreDeclarationDto.CreatedDate;
                get.ItemStatus = shipStoreDeclarationDto.ItemStatus;
                get.DocumentId = shipStoreDeclarationDto.DocumentId;
                get.ModifyId = shipStoreDeclarationDto.ModifyId;
                get.IsTemp = shipStoreDeclarationDto.IsTemp;

                // Delete all ship store item
                if (uploadType == enumUploadType.Replace)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.ShipStoreItems)
                    {
                        lstGuidId.Add(item.ShipStoreItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteShipStoreItem(id);
                    }
                }

                // Add and Update
                foreach (var item in shipStoreDeclarationDto.ShipStoreItems)
                {
                    get.ShipStoreItems.Add(ConvertShipStoreItemDtoToModel(item));
                }
            }
            else
            {
                // Insert
                get = ConvertShipStoreDeclarationDtoToModel(shipStoreDeclarationDto);

                // Add and Update
                foreach (var item in shipStoreDeclarationDto.ShipStoreItems)
                {
                    get.ShipStoreItems.Add(ConvertShipStoreItemDtoToModel(item));
                }

                eManifestModel.ShipStoreDeclarations.AddObject(get);
            }
        }

        #endregion

        #region Import Crews

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportCrewsData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // Crews
                ImportCrewsData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhập danh sách thuyền viên");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import crews object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportCrewsData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.UploadType == enumUploadType.Replace)
                DeleteCrewByDocumentId_Sub(documentDto.DocumentId, (Guid)documentDto.Crews[0].CreaterId, isTemp);

            if (documentDto.Crews != null)
            {
                // Add
                foreach (var item in documentDto.Crews)
                {
                    item.IsTemp = isTemp;
                 //   SaveCrew_Sub(item);
                    ImportCrewXMLDetail(documentDto.Crews, documentDto.UploadType);
                }

            }
        }

        #endregion

        #region Import CrewEffectDeclarations

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportCrewEffectDeclarationsData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // CrewEffectDeclarations
                ImportCrewEffectDeclarationsData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhập bản khai hành lý thuyền viên");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import CrewEffectDeclarations object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportCrewEffectDeclarationsData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.UploadType == enumUploadType.Replace)
                DeleteCrewEffectDeclarationByDocumentId_Sub(documentDto.DocumentId, (Guid)documentDto.CrewEffectDeclarations[0].CreaterId, isTemp);

            if (documentDto.CrewEffectDeclarations != null)
            {
                // Add
                foreach (var item in documentDto.CrewEffectDeclarations)
                {
                    item.IsTemp = isTemp;
                   // SaveCrewEffectDeclaration_Sub(item);
                    
                }

                ImportCrewEffectDeclarationXML(documentDto.CrewEffectDeclarations, documentDto.UploadType);
                
            }
        }

        #endregion

        #region Import Passengers

        /// <summary>
        /// Import Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto ImportPassengersData(DocumentDto documentDto, Guid userId, string userName)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                // Passengers
                ImportPassengersData_Sub(documentDto, get);

                //Save DocumentHistory
                SaveDocumentHistory(get, userId, userName, "Cập nhập danh sách hành khách");

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Import passengers object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <param name="get"></param>
        private void ImportPassengersData_Sub(DocumentDto documentDto, Document get)
        {
            var isTemp = IsSubmitDocument(documentDto.DocumentId);

            if (documentDto.UploadType == enumUploadType.Replace)
                DeletePassengerByDocumentId_Sub(documentDto.DocumentId, (Guid)documentDto.Passengers[0].CreaterId, isTemp);

            if (documentDto.Passengers != null)
            {
                // Add
                foreach (var item in documentDto.Passengers)
                {
                    item.IsTemp = isTemp;
                    SavePassenger_Sub(item);
                }
            }
        }

        #endregion

    }
}
